<?php
namespace backend\component;


use yii\base\Component;
use yii\db\Exception;

class Logger extends Component
{
    /**
     * 关联的表类
     * @var
     */
    public $model;
    /**
     * 需要过滤的地址
     * @var
     */
    public $logEvents;
    /**
     * 缓存
     * @var
     */
    public $cacheId;


    public function init()
    {
        parent::init();
        if ($this->model && is_string($this->model)) {
            $this->model = new $this->model();
        }
    }


    public function logging($data) {
        if (is_object($this->model)){
            foreach ($data as $item) {
                $this->model->$item = $this->buildData($item);
            }
        }
        try{
            if ($this->model->save()) {
                return true;
            } else {
                \Yii::error("操作记录保存失败");
                return false;
            }
        }catch (Exception $e) {
            \Yii::error($e->getMessage());
            return false;
        }
        return true;
    }


    private function buildData($val) {
        if (empty($val)) return "";
        $result = "";
        switch ($val) {
            case "ip_address":
                $result = ip2long(\Yii::$app->request->getUserIP());
                break;
            case "user_id":
                $result =  \Yii::$app->user->getId();
                break;
            case "desc":
                $result = $this->getEventName();
                break;
            case "op_data":
                $result = $this->getRequestData();
                break;
        }
        return $result;
    }


    private function getEventName() {
        $key = strtolower(\Yii::$app->controller->getRoute());
        if ($key) {
           return isset($this->logEvents[$key]) ? $this->logEvents[$key] : "unknown";
        }
        return 'unknown';
    }


    private function getRequestData() {
        return json_encode($_REQUEST);
    }


    /**
     * 检查事件是否存在
     * @param $action
     * @return bool
     */
    public function auth($action) {
        if ($this->logEvents && is_array($this->logEvents)) {
            if ($action && array_key_exists($action,$this->logEvents)) {
                return true;
            }
        }
        return false;
    }
}